using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Data;
using Adoor.Object;
using NUnit.Framework;

using Adoor.Ouvrages;
using Adoor.Emprunts;
using Adoor.Object.Disconnected;

namespace Biblio.NUnit.Inheritance
{
	[TestFixture]
	public class TestDisconnected : BaseTest
	{
		public ObjectContext Context;
		public StringBuilder SqlTrace;

		[SetUp]
		public void Setup()
		{
			this.Context = CreateContext();

			// Redirect the trace to this.SqlTrace
			this.SqlTrace = new StringBuilder();
			Trace.Listeners.Add(new TextWriterTraceListener(new StringWriter(this.SqlTrace)));

			// Work offline
			this.Context.Disconnected = true;
		}

		[TearDown]
		public void TearDown()
		{
			// No SQL commands should be emitted to the database when we work offline
			Assert(new Regex("SQL:.*\n").Matches(this.SqlTrace.ToString()).Count == 0);
		}

		[Test]
		public void TestForeignKeyFactory()
		{
			Exemplaire exemplaire = CreateExemplaire(Context);
			Livre livre = CreateLivre(Context);
			exemplaire.Ouvrage = livre;
			Assert(exemplaire.Ouvrage == livre);
		}

		[Test]
		public void CollectAfterCreate()
		{
			Ouvrage ouvrage1 = CreateLivre(Context);
			Ouvrage ouvrage2 = CreateLivre(Context);
			Ouvrage ouvrage3 = CreateNumeroRevue(Context);
			ICollection ouvrages = Context.LocalStorage.Collect(typeof(Ouvrage));
			Assert(ouvrages.Count == 3);
			int ouvrage1count = 0;
			int ouvrage2count= 0;
			foreach(Ouvrage o in ouvrages)
			{
				Assert(o == ouvrage1 || o == ouvrage2 || o == ouvrage3);
				if (o == ouvrage1)
					++ouvrage1count;
				if (o == ouvrage2)
					++ouvrage2count;
			}
			Assert(ouvrage1count == 1);
			Assert(ouvrage2count == 1);
		}
	}
}
